<template>
  <el-dialog
    v-model="props.handleVisible"
    title="退还处理"
    :show-close="false"
    :close-on-click-model="false"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-position="top">
      <el-form-item
        label="处理结果"
        prop="dealResult"
        :rules="{
          required: true,
          message: '请选择处理结果',
          trigger: 'change'
        }"
      >
        <el-radio-group v-model="form.dealResult" @change="groupChange">
          <el-radio :label="1">全部退还</el-radio>
          <el-radio :label="2">部分退还</el-radio>
          <el-radio :label="3">未退还</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备件退还列表" prop="detailRequests">
        <div v-show="form.dealResult == 3" style="margin-left: 10px">
          提示：选择未退还时，不可操作备件退还信息，默认退还数量为0
        </div>

        <el-table
          :data="props.handleForm?.partDetailResponses"
          border
          style="width: 100%"
          :span-method="objectSpanMethod"
        >
          <el-table-column prop="partNum" label="备件编号" />
          <el-table-column prop="partName" label="备件名称" />
          <el-table-column prop="partTypeName" label="备件类型" />
          <el-table-column prop="amount" label="申请退还数量" />
          <el-table-column prop="price" label="备件价值(元)" />
          <el-table-column prop="batchNum" label="退还批次" />
          <el-table-column prop="batchAmount" label="批次可退还数量" />
          <el-table-column prop="detailRequests" label="实际退还数量">
            <!-- thNum -->
            <template #default="scope">
              <!-- onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^123456789]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-19]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" -->
              <el-input
                v-model="scope.row.thNum"
                autocomplete="off"
                placeholder="输入数量"
                @input="inputChange(scope.row)"
                maxLength="8"
                :disabled="form.dealResult == 3"
              />
              <!-- <el-input-number
                size="small"
                style="width: 100%"
                v-model="scope.row.thNum"
                :min="0":disabled="!tableSelectedIds.includes(scope.row.partNum)"
                :max="scope.row.batchAmount"
                @change="inputChange(scope.row)"
              /> -->
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="备注信息">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          autocomplete="off"
          placeholder="备注信息"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(formRef)">取消</el-button>
        <el-button type="primary" @click="submit(formRef)"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ElMessage,
  FormInstance,
  FormRules,
  SpanMethodProps
} from 'element-plus'
import { ref, reactive, watch } from 'vue'
import {
  getUsageDetailByApplyNumApi,
  refundAuditPartApplyApi
} from '/@/api/spare'
const emit = defineEmits(['closeHandle', 'submitHandle'])

interface PropsDialog {
  handleVisible: boolean //弹窗是否出现
  handleForm?: object
  totalAmount?: number
}
const props = withDefaults(defineProps<PropsDialog>(), {
  handleVisible: false
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const form = ref({
  dealResult: '' as any,
  refundId: '',
  remark: '',
  detailRequests: [
    {
      partId: '', //备件id
      batchNum: '', //批次号
      amount: '' //数量
    }
  ]
})
watch(
  () => props.handleVisible,
  () => {
    form.value.dealResult = ''
    formRef.value?.clearValidate('dealResult')
    props.handleForm?.partDetailResponses.forEach((element: any) => {
      element.thNum = ''
    })
  }
)
const validatePartDetailResponses = (rule: any, value: any, callback: any) => {
  if (form.value.detailRequests.length == 0) {
    callback(new Error('请选择退还列表'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  dealResult: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ],
  detailRequests: [
    {
      required: true,
      validator: validatePartDetailResponses,
      trigger: 'blur'
    }
  ]
})
const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  close()
}

const close = () => {
  emit('closeHandle')
}
const submit = (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      let n = 0
      form.value.detailRequests.forEach((i: any) => {
        n += i.amount - 0
      })
      if (
        props.handleForm?.refundAmount > n &&
        n >= 0 &&
        form.value.dealResult == 1
      ) {
        ElMessage.warning('未全部退还')
      } else if (
        n == 0 &&
        (form.value.dealResult == 2 || form.value.dealResult == 1)
      ) {
        ElMessage.warning('备件未退还')
      } else if (
        n == props.handleForm?.refundAmount &&
        (form.value.dealResult == 2 || form.value.dealResult == 3)
      ) {
        ElMessage.warning('请选择全部退还')
      } else if (n != 0 && form.value.dealResult == 3) {
        ElMessage.warning('请选择正确处理结果')
      } else {
        form.value.refundId = props.handleForm?.id
        refundAuditPartApplyApi(form.value).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '退还成功'
            })
            emit('submitHandle')
          }
        })
      }
    }
  })
}

const inputChange = (val: any) => {
  // @input="(v) => (scope.row.thNum = v.replace(/[^\d]/g, ''))"
  val.thNum = val.thNum.replace(/[^\d]/g, '')
  let t = 0
  if (val.thNum > val.batchAmount) {
    ElMessage({
      type: 'warning',
      message: '退还数量不能大于当前批次可退还数量'
    })
    val.thNum = ''
  } else {
    for (let index = 0; index < form.value.detailRequests.length; index++) {
      let i = form.value.detailRequests[index]
      if (i.partId == val.partId) {
        if (i.batchNum == val.batchNum) {
          i.amount = ''
          t = t - 0 + (val.thNum - 0)
        }
        t += i.amount - 0
        if (t > val.amount) {
          ElMessage({
            type: 'warning',
            message: '退还数量不能大于申请退还数量'
          })
          val.thNum = ''
          return
        } else if (t == val.amount) {
          if (i.batchNum == val.batchNum) {
            i.amount = val.thNum
          }
        } else {
          if (i.batchNum == val.batchNum) {
            i.amount = val.thNum
          }
        }
        if (val.thNum > val.batchAmount) {
          if (i.batchNum == val.batchNum) {
            ElMessage({
              type: 'warning',
              message: '退还数量不能大于当前批次可退还数量'
            })
            val.thNum = ''
            i.amount = ''
          }
          return
        }
      }
    }
  }
}

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex
}: SpanMethodProps) => {
  if (columnIndex < 5) {
    if (rowIndex === row.rowNum && row.num != 1) {
      return {
        rowspan: row.num,
        colspan: 1
      }
    }
    if (row.rowNum === 0 && rowIndex != 0 && rowIndex <= row.num - 1) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    if (rowIndex > row.rowNum && rowIndex <= row.rowNum * row.num) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

const groupChange = (val: any) => {
  if (val == 3) {
    props.handleForm?.partDetailResponses.forEach((element: any) => {
      element.thNum = 0
    })
  } else if (val == 1) {
    props.handleForm?.partDetailResponses.forEach((element: any) => {
      element.thNum = 1
    })
  } else {
    props.handleForm?.partDetailResponses.forEach((element: any) => {
      element.thNum = ''
    })
  }
}

watch(
  () => props.handleVisible,
  () => {
    if (props.handleVisible == true) {
      form.value.detailRequests = []
      form.value.remark = ''
      props.handleForm?.partDetailResponses.forEach((item: any) => {
        let obj = {
          partId: item.partId,
          amount: item.thNum,
          batchNum: item.batchNum
        }
        form.value.detailRequests.push(obj)
      })
    }
  }
)
</script>
<style scoped lang="scss"></style>
